import { filterParams, sortedJsonString } from "@/utils";
import { isDevEnv } from "@/utils/env";
import axios from "axios";

const CancelToken = axios.CancelToken;
const httpMap = new Map();
function getHttpKey(config: any) {
  let { url, method, data, params } = config;
  data = isString(data) ? data : JSON.stringify(data);
  params = isString(params) ? params : JSON.stringify(params);
  return `url=${url}&method=${method}&data=${data}&params=${params}`;
}
function addHttp(config: any) {
  const httpKey = getHttpKey(config);
  if (httpMap.has(httpKey)) {
    const source = CancelToken.source();
    config.cancelToken = source.token;
    source.token.reason = {
      message: `【${config.url}】有相同请求未完成，请勿重复请求`
    };
    source.cancel();
  } else {
    httpMap.set(httpKey, true);
  }
}
function removeHttp(config: any) {
  if (config) {
    const httpKey = getHttpKey(config);
    httpMap.delete(httpKey);
  }
}
// function clearHttp() {
//   httpMap.clear();
// }
const instance = axios.create({
  baseURL: isDevEnv
    ? import.meta.env.VITE_PROXY_URL
    : import.meta.env.VITE_TARGET,
  timeout: 1000 * 60 * 10,
  headers: {
    "Content-Type": "application/json"
  }
});
export const $secretKey = "ramadan2025";
import CryptoJS from "crypto-js";
instance.interceptors.request.use(
  config => {
    if (!isEmptyType(config.params)) {
      config.params = filterParams(config.params);
      const params = sortedJsonString(config.params) + $secretKey;
      config.headers["sign"] = CryptoJS.MD5(params).toString();
    }
    if (!isFormData(config.data)) {
      addHttp(config);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  response => {
    removeHttp(response.config);
    return response.data;
  },
  error => {
    removeHttp(error.config);
    return Promise.reject(error);
  }
);

instance.defaults.headers.common["Content-Type"] = "application/json";
export default instance;
